<template>
  <div class="ml-2 flex-1">
    <div>
      <a-card :bordered="false" style="height: 820px">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="操作人" name="operator">
            <a-tree-select
              v-model:value="searchForm.operator"
              tree-data-simple-mode
              allow-clear
              style="width: 260px"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="selectList"
              placeholder="请选择操作人"
              :load-data="onLoadData"
            />
          </a-form-item>
          <a-form-item label="名单类型">
            <a-select
              v-model:value="searchForm.blacklistType"
              placeholder="请选择名单类型"
              allowClear
            >
              <a-select-option
                v-for="option in listTypeOptions"
                :key="option.value"
                :value="option.value"
              >
                {{ option.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="热力卡号">
            <a-input
              v-model:value="searchForm.alipayConsNo"
              placeholder="请输入热力卡号"
              allowClear
            />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleSearch"
              ><SearchOutlined />查询</a-button
            >
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleReset"
              ><ReloadOutlined />重置</a-button
            >
          </a-form-item>
          <a-form-item>
            <a-button
              type="primary"
              @click="onAdd('停供黑名单')"
              v-if="authInfo.adds == 1"
              ><PlusOutlined />新增停供黑名单</a-button
            >
          </a-form-item>
          <a-form-item>
            <a-button
              type="primary"
              @click="onAdd('缴费黑名单')"
              v-if="authInfo.adds == 1"
              ><PlusOutlined />新增缴费黑名单</a-button
            >
          </a-form-item>
          <a-form-item>
            <a-button
              type="primary"
              @click="onAdd('待补充信息名单')"
              v-if="authInfo.adds == 1"
              ><PlusOutlined />新增待补充信息名单</a-button
            >
          </a-form-item>
          <a-form-item>
            <a-button type="primary" v-if="authInfo.deletes == 1"
              ><DeleteOutlined />批量删除</a-button
            >
          </a-form-item>
          <a-form-item>
            <a-button
              type="primary"
              @click="visible = true"
              v-if="authInfo.imports == 1"
              ><CloudUploadOutlined />客户名单导入</a-button
            >
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="isHistory = true"
              ><HistoryOutlined />导入历史</a-button
            >
          </a-form-item>
        </a-form>
        <a-table
          :columns="columns"
          :data-source="dataSource"
          :pagination="pagination"
        >
          <template #bodyCell="{ column, text, record }">
            <template v-if="column.dataIndex == 'action'">
              <a-space>
                <a-popconfirm
                  title="确定删除吗？"
                  placement="bottom"
                  ok-text="是"
                  cancel-text="否"
                  @confirm="onDelete(record)"
                >
                  <a-button type="link" danger v-if="authInfo.deletes == 1"
                    >删除</a-button
                  >
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
    <a-modal :visible="visible" @cancel="visible = false" @ok="handleOk">
      <div>
        <div>
          <span>1.下载批量导入模版</span>
          <a-divider />
        </div>
        <div class="mb-5">
          <div>
            <span>根据提示信息完善表格内容</span>
          </div>
          <a-button type="primary" class="mt-3" @click="downloadTemplate"
            ><DownloadOutlined />客户名单导入模板.xls</a-button
          >
        </div>
        <div>
          <span>2.导入客户名单导入模板</span>
          <a-divider />
        </div>
        <a-upload-dragger
          v-model:fileList="fileList"
          name="file"
          :multiple="true"
          action="/api/ChargeSystem/customerListMaintenance/verifyCustomerList"
          :headers="header"
          @change="handleChange"
          :beforeUpload="beforeUpload"
          accept=".xls,.xlsx,.et"
          class="mt-3"
        >
          <p class="ant-upload-drag-icon">
            <inbox-outlined></inbox-outlined>
          </p>
          <p class="ant-upload-text">点击/拖拽文件上传</p>
          <p class="ant-upload-hint">
            请将填写好的文件拖拽至此，或点击选择文件
          </p>
          <p class="ant-upload-hint">
            (仅支持.xls、.xlsx、.et格式文件，文件大小限制2MB以内)
          </p>
        </a-upload-dragger>
      </div>
    </a-modal>
    <a-modal
      :visible="isHistory"
      @cancel="isHistory = false"
      title="导入历史"
      width="1400px"
      :model="historyForm"
    >
      <a-form layout="inline">
        <a-form-item label="操作人">
          <a-select
            v-model:value="historyForm.operatorId"
            placeholder="请选择操作人"
            allowClear
          />
        </a-form-item>
        <a-form-item label="机构">
          <a-select
            v-model:value="historyForm.companyId"
            placeholder="请选择机构"
            allowClear
          />
        </a-form-item>
        <a-form-item label="文件名">
          <a-input
            v-model:value="historyForm.fileName"
            placeholder="请输入文件名"
          />
        </a-form-item>
        <a-form-item label="文件类型">
          <a-select
            v-model:value="historyForm.companyId"
            placeholder="请选择机构"
            allowClear
          />
        </a-form-item>
        <a-form-item label="导入结果">
          <a-select
            v-model:value="historyForm.importStatus"
            placeholder="请选择导入结果"
            allowClear
          />
        </a-form-item>
        <a-form-item label="导入日期">
          <a-range-picker
            v-model:value="historyForm.importDate"
            placeholder="请选择导入日期"
            allowClear
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="onHistory">搜索</a-button>
        </a-form-item>
      </a-form>
      <a-table
        :columns="historyColumns"
        :data-source="historyDataSource"
        bordered
        :pagination="historyPagination"
        class="mt-5"
        :row-class-name="
          (_record: any, index: number) =>
            index % 2 === 1 ? 'table-striped' : null
        "
      >
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.dataIndex === 'active'">
            <a-button type="link" @click="onDown(record)">下载</a-button>
          </template>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, h } from 'vue';
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  DeleteOutlined,
  CloudUploadOutlined,
  DownloadOutlined,
  InboxOutlined,
  HistoryOutlined,
} from '@ant-design/icons-vue';
import { useAccessStore } from '@vben/stores';
import { message } from 'ant-design-vue';
import * as netData from '#/api/core/customerInformation';
import { useRoute } from 'vue-router';
import { getAccountButtonAuth } from '#/api/core/auth';
import { getOperatorApi } from '#/api/core/statistical';

const authInfo = ref({});
const router = useRoute();
const getAuth = () => {
  const query = {
    pageId: router.meta.id,
    userId: localStorage.getItem('userId'),
  };
  getAccountButtonAuth(query).then((res: any) => {
    // console.log(res)
    authInfo.value = res.data.data;
  });
  // console.log(router);
};
getAuth();
const props = defineProps({
  selectedNodeId: {
    type: Array,
    default: [],
  },
});
const selectList = ref([]);
const getList = () => {
  getOperatorApi(null)
    .then((res: any) => {
      // console.log(res);
      selectList.value = res.map((item: any) => {
        return {
          id: item.id,
          value: item.id,
          title: item.name,
          key: item.id,
          isLeaf: !!item.userId, // 如果有userId说明是叶子节点
        };
      });
    })
    .catch((error) => {
      console.error('获取操作人员列表失败:', error);
      message.error('获取操作人员列表失败');
    });
};
getList();
const onLoadData = (treeNode: any) => {
  return new Promise((resolve) => {
    // console.log(treeNode);
    // 如果是叶子节点，直接返回
    if (treeNode.isLeaf) {
      resolve(undefined);
      return;
    }

    // 加载子节点数据
    getOperatorApi(treeNode.id)
      .then((res: any) => {
        const children = res.map((item: any) => {
          // console.log(item);
          return {
            id: item.userId ? item.userId : item.id,
            value: item.name ? item.name : item.name,
            title: item.name,
            key: item.userId ? item.userId : item.id,
            isLeaf: !!item.userId, // 如果有userId说明是叶子节点
          };
        });

        // 找到对应的节点并更新其children
        const updateNode = (nodes: any[]) => {
          for (let node of nodes) {
            if (node.key === treeNode.id) {
              node.children = children;
              return true;
            }
            if (node.children && updateNode(node.children)) {
              return true;
            }
          }
          return false;
        };

        updateNode(selectList.value);
        selectList.value = [...selectList.value];
        // console.log(selectList.value);
        resolve(undefined);
      })
      .catch((error) => {
        console.error('加载子节点失败:', error);
        message.error('加载子节点失败');
        resolve(undefined);
      });
  });
};
const searchForm = reactive({
  operatorId: undefined,
  blacklistType: undefined,
  alipayConsNo: '',
});
const historyForm = reactive({
  operatorId: undefined,
  companyId: undefined,
  fileName: '',
  importStatus: undefined,
  importDate: undefined,
});
const initialSearchForm = {
  operator: '',
  listType: '',
  cardNumber: '',
};
const columns = [
  {
    title: '小区名称',
    dataIndex: 'village',
    key: 'village',
    align: 'center',
  },
  {
    title: '用户地址',
    dataIndex: 'address',
    key: 'address',
    align: 'center',
  },
  {
    title: '热力卡号',
    dataIndex: 'alipayConsNo',
    key: 'alipayConsNo',
    align: 'center',
  },
  {
    title: '住户姓名',
    dataIndex: 'holder',
    key: 'holder',
    align: 'center',
  },
  {
    title: '名单类型',
    dataIndex: 'blacklistType',
    key: 'blacklistType',
    align: 'center',
  },
  {
    title: '操作人',
    dataIndex: 'operatorName',
    key: 'operatorName',
    align: 'center',
  },
  {
    title: '操作时间',
    dataIndex: 'operationTime',
    key: 'operationTime',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'center',
  },
];
const historyColumns = [
  {
    title: '文件名',
    dataIndex: 'fileName',
    key: 'fileName',
    align: 'center',
  },
  {
    title: '操作日期',
    dataIndex: 'operateTime',
    key: 'operateTime',
    align: 'center',
  },
  {
    title: '文件数',
    dataIndex: 'fileNumber',
    key: 'fileNumber',
    align: 'center',
  },
  {
    title: '操作人',
    dataIndex: 'operator',
    key: 'operator',
    align: 'center',
  },
  {
    title: '归属机构',
    dataIndex: 'companyName',
    key: 'companyName',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'importStatus',
    key: 'importStatus',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'active',
    key: 'active',
    align: 'center',
  },
];
const historyDataSource = ref([]);
const dataSource = ref([]);
const allData = ref([]);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
  },
});
const historyPagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    historyPagination.current = page;
    historyPagination.pageSize = pageSize;
    onHistory();
  },
});
const visible = ref(false);
const isHistory = ref(false);
const fileList = ref([]);
const accessStore = useAccessStore();
const header = {
  Authorization: accessStore.accessToken || localStorage.getItem('token'),
};
const downloadTemplate = () => {
  // 从public目录下下载文件
  // window.location.href = '/public/开关栓状态导入模版.xls';
  const templatePath = '/Execl/客户名单导入模板.xls';
  const link = document.createElement('a');
  link.href = templatePath;
  link.download = templatePath.split('/').pop() || '';
  document.body.append(link);
  link.click();
  link.remove();
};

const beforeUpload = (file: File) => {
  const isExcel =
    file.type === 'application/vnd.ms-excel' ||
    file.type ===
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  if (!isExcel) {
    message.error('只能上传 .xls, .xlsx, .et 格式的文件!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('文件大小不能超过 2MB!');
  }
  return isExcel && isLt2M;
};
const fileLocation = ref('');
const fileName = ref('');
const fileNumber = ref('');
const handleChange = (info: any) => {
  console.log(info);
  if (info.file.status === 'done') {
    if (info.file.response && info.file.response.code === 0) {
      message.success(`${info.file.name} 文件上传成功`);
      fileLocation.value = info.file.response.data.fileLocation;
      fileName.value = info.file.response.data.fileName;
      fileNumber.value = info.file.response.data.fileNumber;
    } else {
      message.error(
        `${info.file.name} 文件上传失败: ${info.file.response ? info.file.response.message : '未知错误'}`,
      );
    }
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 文件上传失败.`);
  }
};
// 选项数据
const operatorOptions = ref([
  { value: '李管理员', label: '李管理员' },
  { value: '张管理员', label: '张管理员' },
  { value: '王管理员', label: '王管理员' },
  { value: '赵管理员', label: '赵管理员' },
]);

const listTypeOptions = ref([
  { value: '停供黑名单', label: '停供黑名单' },
  { value: '缴费黑名单', label: '缴费黑名单' },
  { value: '待补充信息名单', label: '待补充信息名单' },
]);

// 搜索功能
const handleSearch = () => {
  const query = {
    page: pagination.current,
    limit: pagination.pageSize,
    treeNode: props.selectedNodeId,
    operatorId: searchForm.operatorId ?? '',
    blacklistType: searchForm.blacklistType ?? '',
  };
  netData.getCustomerLabel(query).then((res: any) => {
    console.log(res);
    dataSource.value = res.data.data;
    pagination.total = res.data.count;
  });
};

// 重置功能
const handleReset = () => {
  Object.assign(searchForm, initialSearchForm);
  dataSource.value = [...allData.value];
  pagination.total = allData.value.length;
  pagination.current = 1;
};

const userOptions = ref([]);
const onAdd = (type: string) => {
  const query = {
    treeNode: props.selectedNodeId,
    blacklistType: type,
  };
  netData.addCustomerLabel(query).then((res: any) => {
    message.success(res.data.data);
  });
};
const onDelete = (record: any) => {
  const query = {
    houseID: record.houseID,
    blacklistType: record.blacklistType,
  };
  netData.deleteCustomerLabel(query).then((res: any) => {
    console.log(res);
    if (res.data.code === 200) {
      message.success(res.data.data);
      handleSearch();
    } else {
      message.error(res.data.data);
    }
  });
};
const handleOk = () => {
  netData
    .importCustomerLabel({
      fileLocation: fileLocation.value,
      fileName: fileName.value,
      fileNumber: fileNumber.value,
    })
    .then((res: any) => {
      console.log(res);
      if (res.data.code === 200) {
        message.success(res.data.msg);
        handleSearch();
        visible.value = false;
      } else {
        message.error('导入失败');
      }
    });
};
const onHistory = () => {
  const query = {
    page: historyPagination.current,
    limit: historyPagination.pageSize,
    operatorId: historyForm.operatorId ?? '',
    companyId: historyForm.companyId ?? '',
    fileName: historyForm.fileName ?? '',
    importStatus: historyForm.importStatus ?? '',
    importDate: historyForm.importDate ?? '',
  };
  netData.importCustomerHistory(query).then((res: any) => {
    // console.log(res);
    historyPagination.total = res.data.count;
    historyDataSource.value = res.data.data;
  });
};
const onDown = (e: any) => {
  // console.log(e);
  const loading = message.loading({
    content: "下载中...",
    duration: 0,
  });

  try {
    // 下载地址拼接
    const url = e.urlAddress;

    // 使用a标签下载，避免X-Frame-Options错误
    const link = document.createElement("a");
    link.href = url;
    link.download = ""; // 触发下载而不是导航
    link.target = "_blank";
    link.style.display = "none";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 关闭loading
    setTimeout(() => {
      loading();
    }, 1000);
  } catch (error) {
    console.error("下载出错:", error);
    message.error("下载出错，请重试");
    loading();
  }
};
</script>
<style scoped>
.ant-form-item {
  margin-bottom: 10px;
}
</style>
